//
//  UIButton+XYFixMultiClick.m
//  面试总结
//
//  Created by lxy on 2017/11/23.
//  Copyright © 2017年 lxy. All rights reserved.
//  防止多次点击

#import "UIButton+XYFixMultiClick.h"
#import <objc/runtime.h>

@interface UIButton ()
@property (nonatomic, assign) NSTimeInterval xy_acceptEventTime;
@end

@implementation UIButton (XYFixMultiClick)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        SEL originalSelector = @selector(sendAction:to:forEvent:);
        SEL swizzledSelector = @selector(xy_sendAction:to:forEvent:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (success) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        });

}

- (void)xy_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if ([[NSDate date] timeIntervalSince1970] - self.xy_acceptEventTime < self.xy_acceptEventInterval) {
        return;
    }
    if (self.xy_acceptEventInterval > 0) {
        self.xy_acceptEventTime = [[NSDate date] timeIntervalSince1970];
    }
    [self xy_sendAction:action to:target forEvent:event];
    
}


- (NSTimeInterval)xy_acceptEventInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setXy_acceptEventInterval:(NSTimeInterval)xy_acceptEventInterval {
    objc_setAssociatedObject(self, @selector(xy_acceptEventInterval), @(xy_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)xy_acceptEventTime {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setXy_acceptEventTime:(NSTimeInterval)xy_acceptEventTime {
    objc_setAssociatedObject(self, @selector(xy_acceptEventTime), @(xy_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}



@end
